package cn.nxcoder.blog.controller.admin;

import cn.nxcoder.blog.entity.Blog;
import cn.nxcoder.blog.entity.Video;
import cn.nxcoder.blog.service.VideoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * 视频课程页面
 * @author shengwu ni
 * @date 2018/06/03 16:40
 */
@Controller
@RequestMapping("/admin")
public class VideoController {

    @Resource
    private VideoService videoService;

    @GetMapping("/videos")
    public String vedios(Model model) {

        List<Video> videoList = videoService.findAll();
        model.addAttribute("videos", videoList);
        return "admin/videos";
    }

    @GetMapping("/videos/input")
    public String input(Model model) {
        model.addAttribute("video", new Video());
        return "admin/video-input";
    }

    @PostMapping("/addOrUpdateVideo")
    public String post(Video video, Model model, RedirectAttributes attributes) {

        Integer r;
        if (video.getId() == null) {
            r = videoService.save(video);
        } else {
            r = videoService.update(video);
        }

        // 对插入数据库的操作进行校验，验证是否正常插入或更新了
        if (r == null) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/videos";
    }

    @GetMapping("/videos/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {

        Video video = videoService.findById(id);
        model.addAttribute("video", video);
        return "admin/video-input";
    }

    /**
     * 删除博客
     * @param id 博客id
     * @param attributes 用于重定向带数据到前端
     * @return
     */
    @GetMapping("/videos/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {

        Integer res = videoService.deleteById(id);
        if (res != null) {
            attributes.addFlashAttribute("message", "操作成功");
        } else {
            attributes.addFlashAttribute("message", "操作失败");
        }
        return "redirect:/admin/videos";
    }

}
